package com.example.control;

import com.example.domain.t_user;
import com.example.service.AsyncService;
import com.example.utils.MailUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.Map;
import java.util.Random;

@Controller
public class LoginController {

    private Logger logger = LoggerFactory.getLogger(LoginController.class);
    @Autowired
    private AsyncService asyncService;
    //邮箱
    @Autowired
    private MailUtils mailUtils;

    //跳转登陆页面
    @RequestMapping(value = {"/login"})
    public String getLogin(HttpServletRequest request, Map map){
        //获取请求头和url中的原始非拦截的访问路径
        String referer = request.getHeader("Referer");
        String url = request.getParameter("url");

        //如果url中已经封装了原始页面路径，直接返回该路径
        if(url!=null && !"".equals(url)){
            map.put("url",url);
        //如果请求头包含登陆，将重定向url为空，让后台通过用户角色进行跳转
        }else if (referer!=null && referer.contains("/login")){
            map.put("url","");
         //否则，返回请求头的原始访问路径
        }else{
            map.put("url",referer);
        }

        return "comm/login";
    }
    //获取验证码
    @RequestMapping(value = "/login/sendCode")
    @ResponseBody
    public Boolean getCode(HttpServletRequest request,String email){
        try{

            String code = getRandomNum(6);
            //验证码放入session
            request.getSession().setAttribute("userCode", code);
            //设置验证码的时间
            request.getSession().setAttribute("userCode_time", new Date().getTime());

            try{
                asyncService.asyncInvoke(()->{
                    //System.out.println("begin");
                    mailUtils.sendMail(email,
                            "CrazyStone个人博客小站提示你：即将修改登录，本次验证码：" + code + ",有效时间三分钟",
                            "CrazyStone个人博客小站");
                    //System.out.println("sucess");
                });
            }catch(Exception e){
                logger.error("异步线程发送邮箱失败，错误信息："+e.getMessage());
            }
            //System.out.println(true);
            return true;

        }catch (Exception e){
            logger.error("发送验证码失败，错误信息:"+e.getMessage());
            return false;
        }
    }
    private String getRandomNum(int i) {
        Random random = new Random();
        String res="";
        while(i-->0){
            res+=String.valueOf(random.nextInt(10));
        }
        return res;
    }



    //无权限异常访问处理
    @GetMapping("/errorPage/{page}/{code}")
    public String AccessExceptionHandler(@PathVariable("page") String page,
                                         @PathVariable("code") String code){
        return page+"/"+code;
    }
}
